package com.test.study;

import com.test.study.discovery.IDiscovery;
import com.test.study.pojo.GpRpcReq;
import org.springframework.util.StringUtils;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;

public class GpRpcClientInvoke implements InvocationHandler {

	private Class<?> clz;
	private IDiscovery discovery;

	public GpRpcClientInvoke(Class<?> clz, IDiscovery discovery) {
		this.clz = clz;
		this.discovery = discovery;
	}

	@Override
	public Object invoke(Object proxy, Method method, Object[] args)
			throws Throwable {
		// 判断
		if (method.getDeclaringClass().isInterface()) {
			return rpcInvoke(this, method, args);
		}
		return method.invoke(proxy, args);
	}

	public Object rpcInvoke(Object proxy, Method method, Object[] args) {
			GpRpcReq req = new GpRpcReq();
			req.setServiceName(clz.getName());
			req.setMethodName(method.getName());
			req.setVer("v2.0");
			req.setParams(args);

			String serviceName = req.getServiceName();
			//判断版本，组装service
		    if(!StringUtils.isEmpty(req.getVer())){
		    	serviceName = serviceName+"_"+req.getVer();
			}

		String servicePath = this.discovery.discovery(serviceName);
		String[] split = servicePath.split(":");

//		TCPTransport tcpTransport = new TCPTransport(split[0], Integer.parseInt(split[1]));
//			return tcpTransport.send(req);
		NettyTransport nettyTransport = new NettyTransport(split[0], Integer.parseInt(split[1]));
		return nettyTransport.send(req);

	}
}
